import * as THREE from 'three';
import Stats from 'three/examples/jsm/libs/stats.module.js';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { CSS2DRenderer, CSS2DObject  } from "three/examples/jsm/renderers/CSS2DRenderer.js";

import { sceneGroup , floor , hot_cube , hot_map} from "./product.js";
import { config } from './config.js';
import { iconGroup } from './icon.js';

import { productSceneLoop , onReSize} from "./productScene.js";


import { vertexShader } from "../glsl/vertexShader.js";
import { fragmentShader } from "../glsl/fragmentShader.js";


    var scene = new THREE.Scene();
    scene.background = new THREE.Color().setHSL( 0.6, 0, 1 );
    scene.fog = new THREE.Fog(  scene.background, 1000, 3000 );
    scene.add(iconGroup);
    scene.add(floor);

    var clock = new THREE.Clock(); // 创建一个时钟对象Clock

    // GROUND

    const groundGeo = new THREE.PlaneBufferGeometry( 5000, 5000 );
    const groundMat = new THREE.MeshLambertMaterial( { color: 0xffffff } );
    groundMat.color.setHSL( 0.095, 1, 0.75 );

    const ground = new THREE.Mesh( groundGeo, groundMat );
    ground.position.y = - 33;
    ground.rotation.x = - Math.PI / 2;
    
    scene.add( ground );

    //GROUND

    // const gt = new THREE.TextureLoader().load( "textures/grasslight-big.jpg" );
    // const gg = new THREE.CircleBufferGeometry( 2000, 64 );
    // const gm = new THREE.MeshPhongMaterial( { color: 0xffffff, map: gt } );

    // const ground = new THREE.Mesh( gg, gm );
    // ground.position.y = -0.5;
    // ground.rotation.x = - Math.PI / 2;
    // ground.material.map.repeat.set( 64, 64 );
    // ground.material.map.wrapS = THREE.RepeatWrapping;
    // ground.material.map.wrapT = THREE.RepeatWrapping;
    // ground.material.map.encoding = THREE.sRGBEncoding;
    // // note that because the ground does not cast a shadow, .castShadow is left false
    // ground.receiveShadow = true;
    // scene.add( ground );


    // LIGHTS
    const d = 50;

    const hemiLight = new THREE.HemisphereLight( 0xffffff, 0xffffff, 0.6 );
    hemiLight.color.setHSL( 0.6, 1, 0.6 );
    hemiLight.groundColor.setHSL( 0.095, 1, 0.75 );
    hemiLight.position.set( 0, 100, 0 );
    scene.add( hemiLight );

    // const hemiLightHelper = new THREE.HemisphereLightHelper( hemiLight, 10 );
    // scene.add( hemiLightHelper );

    const dirLight_left = new THREE.DirectionalLight( 0xffffff, 0.6 );
    dirLight_left.color.setHSL( 0.1, 1, 0.95 );
    dirLight_left.position.set( 0, 0.7, 1 );
    dirLight_left.position.multiplyScalar( 350 );
    scene.add( dirLight_left );


    const dirLight_right = new THREE.DirectionalLight( 0xffffff, 0.6 );
    dirLight_right.color.setHSL( 0.1, 1, 0.95 );
    dirLight_right.position.set( 0, 0.7, -1 );
    dirLight_right.position.multiplyScalar( 350 );
    scene.add( dirLight_right );


    // const dirLightHelper_left = new THREE.DirectionalLightHelper( dirLight_left, 10 );
    // scene.add( dirLightHelper_left );

    // const dirLightHelper_right = new THREE.DirectionalLightHelper( dirLight_right, 10 );
    // scene.add( dirLightHelper_right );


    // SKYDOME
    const uniforms = {
        "topColor": { value: new THREE.Color( 0x0077ff ) },
        "bottomColor": { value: new THREE.Color( 0xffffff ) },
        "offset": { value: 33 },
        "exponent": { value: 0.6 }
    };
    uniforms[ "topColor" ].value.copy( hemiLight.color );

    scene.fog.color.copy( uniforms[ "bottomColor" ].value );

    const skyGeo = new THREE.SphereBufferGeometry( 2500, 32, 15 );
    const skyMat = new THREE.ShaderMaterial( {
        uniforms: uniforms,
        vertexShader: vertexShader,
        fragmentShader: fragmentShader,
        side: THREE.BackSide
    } );

    const sky = new THREE.Mesh( skyGeo, skyMat );
    scene.add( sky );




	


    scene.add(sceneGroup);
    var stats = new Stats();
    stats.dom.style.top = "80px";
    // document.body.appendChild(stats.dom); 


    var width  = window.innerWidth; //窗口文档显示区的宽度
    var height = window.innerHeight; //窗口文档显示区的高度



	/** 相机设置*/
	var k = width / height; //Three.js输出的Cnavas画布宽高比
	var s = 200; //控制相机渲染空间左右上下渲染范围，s越大，相机渲染范围越大
	// -s * k, s * k, s, -s, 1, 1000定义了一个长方体渲染空间，渲染空间外的模型不会被渲染
	// var camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000);
    var camera = new THREE.PerspectiveCamera( 45, k , 0.1, 4000 );
	camera.position.set(config.cameraInitialPos.x,config.cameraInitialPos.y,config.cameraInitialPos.z); //相机在Three.js坐标系中的位置
	camera.lookAt(0, 0, 0); //相机指向Three.js坐标系原点
	/**
	 * 创建渲染器对象
	 */
    var renderer = new THREE.WebGLRenderer({
        antialias: true, //开启锯齿
    });
    renderer.setPixelRatio(window.devicePixelRatio);//设置设备像素比率,防止Canvas画布输出模糊。
    renderer.setSize(width, height); //设置渲染区域尺寸
    // renderer.outputEncoding = THREE.sRGBEncoding;
    renderer.shadowMap.enabled = true;
      // renderer.domElement表示Three.js渲染结果,也就是一个HTML元素(Canvas画布)



    // 创建一个CSS2渲染器CSS2DRenderer
    var labelRenderer = new CSS2DRenderer();
    labelRenderer.setSize(window.innerWidth, window.innerHeight);
    labelRenderer.domElement.style.position = 'absolute';
    // 相对鼠标单击位置偏移
    labelRenderer.domElement.style.top = '-150px';
    labelRenderer.domElement.style.left = '0px';
    // //设置.pointerEvents=none，以免模型标签HTML元素遮挡鼠标选择场景模型
    labelRenderer.domElement.style.pointerEvents = 'none';

    
    //创建控件对象  控件可以监听鼠标的变化，改变相机对象的属性
	// 旋转：拖动鼠标左键
	// 缩放：滚动鼠标中键
	// 平移：拖动鼠标右键
	var controls = new OrbitControls(camera, renderer.domElement);
    controls.maxPolarAngle = Math.PI / 2 - 0.01;
    // 使动画循环使用时阻尼或自转 意思是否有惯性
    controls.enableDamping = true;
    //动态阻尼系数 就是鼠标拖拽旋转灵敏度
    controls.dampingFactor = 0.25;
    controls.enableZoom = true;
    // controls.autoRotate = true;
    controls.minDistance  = 20;
    controls.maxDistance  = 500;
    controls.enablePan = true;


    // var stack = sceneGroup.getObjectByName("c2");
    // scene.updateMatrixWorld(true);
    // // 声明一个三维向量用来保存网格模型的世界坐标
    // var worldPosition = new THREE.Vector3();
    // // 获得世界坐标，执行getWorldPosition方法，提取网格模型的世界坐标结果保存到参数worldPosition中
    // stack.getWorldPosition(worldPosition)
    // worldPosition.y -= 25 / 2;
    // // controls.target.copy(worldPosition); //相机指向Three.js坐标系原点
    // console.log("查看网格模型世界坐标"+worldPosition);
    // console.log('查看网格模型本地坐标',stack.position);
    // var axesHelper = new THREE.AxesHelper(100);
    // axesHelper.position.copy(worldPosition);
    // scene.add(axesHelper);
    // console.log(controls.target);

    window.addEventListener("resize",onWindowResize,false);

    function onWindowResize() {

        camera.aspect = window.innerWidth/window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(window.innerWidth,window.innerHeight);

        onReSize();
    }

    // controls.addEventListener("change",render);
  
    function render() 
    {
        if(hot_cube.visible){
            // hot_map.offset.x -= 0.01;
            hot_map.offset.y -= 0.05;
        }
        labelRenderer.render(scene,camera);
       	renderer.render( scene , camera );
    }


    function loop()
    {
         // 如果场景显示就渲染
        if(config.isProductScene)
        {
            productSceneLoop();
        }else{
            render();
            controls.update();
        }
       

        stats.update();
        requestAnimationFrame(loop); //请求再次执行渲染函数render，渲染下一帧
    }
    loop();
    render();


    function appendChildDDom(dom){
       dom.appendChild(renderer.domElement); //body元素中插入canvas对象
       dom.appendChild(stats.dom); 
       dom.appendChild(labelRenderer.domElement); //body元素中插入canvas对象
    }


    export { scene , camera , controls , appendChildDDom};



   